import os

from pptx import Presentation
from docx import Document
from flask import request
import re
import logging

#
# def upload_file():
#     if request.method == "POST":
#         file = request.files["file"]
#         if file:
#             filename = file.filename
#             file.save(filename)  # 保存文件到当前目录
#
#             return f"文件 {filename} 上传成功！"

file_path_root = "H:\\"  # windows环境使用
# file_path_root = "/home/will"  # windows环境使用



# file_path_root = "/home/will" # linux环境使用

def upload_file():
    if request.method == "POST":
        file = request.files["file"]
        if file:
            filename = file.filename
            save_path = os.path.join(file_path_root, filename)
            file.save(save_path)
            return extract_ppt_titles(save_path)


def extract_ppt_titles(save_path):
    try:
        prs = Presentation(save_path)

        doc = Document()
        # 遍历每一页PPT
        for slide in prs.slides:

            # 获取标题
            title = slide.shapes.title.text
            doc.add_heading(title, 0)

            # 获取正文
            text = []
            for shape in slide.shapes:
                if not shape.has_text_frame:
                    continue
                for paragraph in shape.text_frame.paragraphs:
                    text.append(paragraph.text)

            # 查找关键词
            keywords = re.findall(r'\w{4,}', ' '.join(text))
            doc.add_paragraph(' '.join(keywords))

            # 获取备注
            notes_slide = slide.notes_slide
            notes_text = notes_slide.notes_text_frame.text
            if notes_text:
                doc.add_paragraph("备注：" + notes_text)

        filename = os.path.splitext(os.path.basename(save_path))[0]
        fileout = file_path_root + filename + ".docx"
        doc.save(fileout)

        return filename + ".docx"
    except Exception as e:
        logging.exception(e)
        return "文件解析失败，请检查文件格式是否正确！"
